<template>
	<div class="owner-container base-page-container">
		<!-- 搜索区域 -->
		<common-search v-model="searchForm" :search-items="searchItemsConfig" @search="handleSearch"
			@reset="fetchTableData" :item-width="200" :label-width="100" @remote-search="handleRemoteSearch">
		</common-search>

		<!-- 操作按钮区域 -->
		<action-buttons 
			:buttons="buttonsConfig"
			:selected-data="selectedRows"
			@add="handleAdd"
			@export="handleExport" 
			@import="handleImport" 
			@enable="handleEnable" 
			@disable="handleDisable" 
			@delete="handleDelete" 
		/>

		<!-- 表格区域 -->
		<custom-table
			:data="tableData"
			:columns="tableColumns"
			:loading="tableLoading"
			:current-page="pagination.currentPage"
			:page-size="pagination.pageSize"
			:total="pagination.total"
			table-id="owner-table"
			@selection-change="handleSelectionChange"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
		>
			<!-- 状态列的自定义插槽 -->
			<template #status="{ row }">
				<el-tag :type="row.status === '启用' ? 'success' : 'info'">
					{{ row.status }}
				</el-tag>
			</template>
			
			<!-- 操作列 -->
			<template #operation="{ row }">
				<theme-button v-if="tablePermissions.edit" link @click="handleEdit(row)">编辑</theme-button>
				<theme-button v-if="tablePermissions.view" link @click="handleView(row)">查看</theme-button>
				<theme-button v-if="tablePermissions.log" link @click="handleLog(row)">日志</theme-button>
			</template>
		</custom-table>

		<!-- 货主信息弹窗 -->
		<el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增货主' : '编辑货主'" width="550px"
			destroy-on-close class="base-dialog" :close-on-click-modal="false">
			<el-form ref="ownerFormRef" :model="ownerForm" :rules="ownerFormRules" label-width="80px"
				class="base-form">
				<div class="form-row">
					<el-form-item label="货主编号" prop="code" required>
						<el-input v-model="ownerForm.code" placeholder="请输入货主编号"></el-input>
					</el-form-item>
					<el-form-item label="货主名称" prop="name" required>
						<el-input v-model="ownerForm.name" placeholder="请输入货主名称"></el-input>
					</el-form-item>
				</div>

				<div class="form-row">
					<el-form-item label="货主地址" prop="region" required>
						<region-cascader v-model="ownerForm.region" placeholder="请选择所在区域" :level="3" :separator="'/'"
							style="width: 100%" filterable clearable :use-code-data="false" :return-code="false" />
					</el-form-item>
				</div>

				<div class="form-row full-width">
					<el-form-item label="详细地址" prop="address" class="full-width-item">
						<el-input v-model="ownerForm.address" placeholder="请输入详细地址，如街道、门牌号等" 
							show-word-limit type="textarea" rows="3"></el-input>
					</el-form-item>
				</div>

				<div class="form-row">
					<el-form-item label="邮编" prop="zipCode">
						<el-input v-model="ownerForm.zipCode" placeholder="请输入邮编"></el-input>
					</el-form-item>
					<el-form-item label="联系人" prop="contactPerson">
						<el-input v-model="ownerForm.contactPerson" placeholder="请输入联系人"></el-input>
					</el-form-item>
				</div>

				<div class="form-row">
					<el-form-item label="固话" prop="telephone">
						<el-input v-model="ownerForm.telephone" placeholder="请输入固话"></el-input>
					</el-form-item>
					<el-form-item label="手机号" prop="contactPhone">
						<el-input v-model="ownerForm.contactPhone" placeholder="请输入手机号"></el-input>
					</el-form-item>
				</div>

				<div class="form-row full-width">
					<el-form-item label="备注" prop="remark" class="full-width-item">
						<el-input v-model="ownerForm.remark" placeholder="请输入备注" type="textarea" rows="3"></el-input>
					</el-form-item>
				</div>

				<div class="form-row full-width">
					<el-form-item label="授权分仓" prop="warehouses" required>
						<el-select v-model="ownerForm.warehouses" multiple placeholder="请选择授权分仓" style="width: 100%">
							<el-option label="华东杭州分仓" value="华东杭州分仓"></el-option>
							<el-option label="华南苏州分仓" value="华南苏州分仓"></el-option>
							<el-option label="华北上海分仓" value="华北上海分仓"></el-option>
						</el-select>
					</el-form-item>
				</div>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitForm">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 日志弹窗 -->
		<log-dialog
			v-model:visible="logDialogVisible"
			:log-data="logData"
			:total="logPagination.total"
			:current-page="logPagination.currentPage"
			:page-size="logPagination.pageSize"
			@size-change="handleLogSizeChange"
			@current-change="handleLogCurrentChange"
		/>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		watch
	} from 'vue'
	import {
		useTheme
	} from '@/hooks/useTheme'
	import {
		RegionCascader
	} from '@/components/common'
	import { ElMessage } from 'element-plus'

	// 使用主题组合API
	const {
		themeType
	} = useTheme()

	// 判断是否开发环境
	const isDevelopment = computed(() => {
		return import.meta.env.MODE === 'development'
	})

	// 搜索项配置列表
	const searchItemsConfig = [{
			label: '货主编号',
			prop: 'code',
			type: 'el-input',
			placeholder: '请输入货主编号',
			defaultVisible: true,
			width: 180
		},
		{
			label: '货主名称',
			prop: 'name',
			type: 'el-input',
			placeholder: '请输入货主名称',
			defaultVisible: true
		},
		{
			label: '状态',
			prop: 'status',
			type: 'el-select',
			placeholder: '请选择状态',
			defaultVisible: true,
			width: '250px',
			options: [{
					label: '请选择状态',
					value: ''
				},
				{
					label: '启用',
					value: '启用'
				},
				{
					label: '停用',
					value: '停用'
				}
			]
		},
		// {
		// 	label: '所在地区',
		// 	prop: 'regionSearch',
		// 	type: 'region-cascader',
		// 	placeholder: '请选择所在地区',
		// 	defaultVisible: true,
		// 	level: 3,
		// 	separator: '/',
		// 	useCodeData: false,
		// 	returnCode: false,
		// 	filterable: true,
		// 	clearable: true
		// },
		// {
		// 	label: '创建日期',
		// 	prop: 'createDate',
		// 	type: 'el-date-picker',
		// 	placeholder: '请选择创建日期',
		// 	defaultVisible: true,
		// 	dateType: 'date',
		// 	format: 'YYYY-MM-DD',
		// 	valueFormat: 'YYYY-MM-DD'
		// },
		// {
		// 	label: '联系人',
		// 	prop: 'contactPerson',
		// 	type: 'el-input',
		// 	placeholder: '请输入联系人',
		// 	defaultVisible: false
		// },
		// {
		// 	label: '联系电话',
		// 	prop: 'contactPhone',
		// 	type: 'el-input',
		// 	placeholder: '请输入联系电话',
		// 	defaultVisible: false
		// },
		// {
		// 	label: '所属仓库',
		// 	prop: 'warehouse',
		// 	type: 'el-select',
		// 	placeholder: '搜索仓库',
		// 	defaultVisible: true,
		// 	remote: true,
		// 	loading: false,
		// 	filterable: true,
		// 	width: '250px',
		// 	options: [{ label: '所有仓库', value: '' }],
		// 	remoteOptions: []
		// },
		// {
		// 	label: '日期范围',
		// 	prop: 'dateRange',
		// 	type: 'el-date-picker',
		// 	placeholder: '请选择日期范围',
		// 	defaultVisible: false,
		// 	dateType: 'daterange',
		// 	format: 'YYYY-MM-DD',
		// 	valueFormat: 'YYYY-MM-DD',
		// 	startPlaceholder: '开始日期',
		// 	endPlaceholder: '结束日期',
		// 	rangeKeys: ['startDate', 'endDate']
		// }
	]

	// 操作按钮配置
	const buttonsConfig = ref({
		add: { visible: true, order: 1, type: 'success' },
		delete: { visible: true, order: 4, type: 'danger' },
		export: { visible: false, order: 3, type: themeType },
		import: { visible: false, order: 4, type: themeType },
		enable: { visible: true, order: 2, type: themeType },
		disable: { visible: true, order: 3, type: themeType },
		viewLog: { visible: false, order: 7 },
		edit: { visible: false, order: 8 }
	})

	// 表格操作权限
	const tablePermissions = ref({
		edit: true,
		view: true,
		log: true
	})

	// 搜索表单数据
	const searchForm = reactive({
		code: '',
		name: '',
		status: '',
		createDate: '',
		contactPerson: '',
		contactPhone: '',
		warehouse: '',
		dateRange: [],
		regionSearch: ''
	})

	// 表格数据相关
	const tableData = ref([])
	const tableLoading = ref(false)
	const selectedRows = ref([])

	// 分页相关
	const pagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 货主表单相关
	const ownerFormRef = ref(null)
	const dialogVisible = ref(false)
	const dialogType = ref('add') // 'add' 或 'edit'
	const ownerForm = reactive({
		id: '',
		code: '',
		name: '',
		region: '',
		address: '',
		zipCode: '',
		contactPerson: '',
		contactPhone: '',
		telephone: '',
		warehouse: '',
		remark: '',
		warehouses: []
	})

	// 表单校验规则
	const ownerFormRules = {
		code: [{
			required: true,
			message: '请输入货主编号',
			trigger: 'blur'
		}],
		name: [{
			required: true,
			message: '请输入货主名称',
			trigger: 'blur'
		}],
		region: [{
			required: true,
			message: '请选择所在区域',
			trigger: 'change'
		}],
		contactPerson: [{
			required: true,
			message: '请输入联系人',
			trigger: 'blur'
		}],
		contactPhone: [{
			required: true,
			message: '请输入联系电话',
			trigger: 'blur'
		}],
		warehouses: [{
			validator: (rule, value, callback) => {
				if (value.length === 0) {
					callback(new Error('请至少选择一个授权分仓'))
				} else {
					callback()
				}
			},
			trigger: 'change'
		}]
	}

	// 监听region字段变化
	watch(() => ownerForm.region, (newVal) => {
		console.log('货主地址变化:', newVal);
	}, { immediate: true });

	// 日志弹窗相关
	const logDialogVisible = ref(false)
	const logData = ref([])
	const logPagination = reactive({
		currentPage: 1,
		pageSize: 10,
		total: 0
	})

	// 表格列配置
	const tableColumns = ref([
		{ prop: 'code', label: '货主编号', width: '120', minWidth: '120', visible: true },
		{ prop: 'name', label: '货主名称', width: '120', minWidth: '120', visible: true },
		{ prop: 'status', label: '状态', width: '80', minWidth: '80', visible: true },
		{ prop: 'contactPerson', label: '联系人', width: '100', minWidth: '100', visible: true },
		{ prop: 'contactPhone', label: '手机号', width: '120', minWidth: '120', visible: true },
		{ prop: 'address', label: '货主地址', minWidth: '180', visible: true },
		{ prop: 'warehouse', label: '所属仓库', width: '150', minWidth: '150', visible: true },
		{ prop: 'remark', label: '备注', width: '150', minWidth: '150', visible: true },
		{ prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true }
	])

	// 计算表格高度
	const tableHeight = computed(() => {
		// 考虑页面其他元素高度，加大减去的值以确保有足够的空间
		// 大约 180px 为搜索区域和操作按钮的高度，70px 为分页器和边距
		return window.innerHeight - 250;
	})

	// 获取表格数据
	const fetchTableData = async () => {
		tableLoading.value = true

		try {
			// 模拟异步请求
			if (isDevelopment.value) {
				setTimeout(() => {
					// 模拟数据
					tableData.value = [{
							id: '1',
							code: '005',
							name: 'E货主',
							status: '启用',
							contactPerson: '王某',
							contactPhone: '15349896789',
							address: '浙江省杭州市西湖区西溪大道XXXXX',
							warehouse: '华东杭州仓',
							remark: ''
						},
						{
							id: '2',
							code: '004',
							name: 'D货主',
							status: '启用',
							contactPerson: '赵某',
							contactPhone: '15489896789',
							address: '浙江省杭州市西湖区XXXXX',
							warehouse: '华东苏州仓',
							remark: ''
						},
						{
							id: '3',
							code: '003',
							name: 'C货主',
							status: '启用',
							contactPerson: '李某',
							contactPhone: '15389896789',
							address: '江苏省苏州市吴中区XXXXX',
							warehouse: '华东苏州仓',
							remark: ''
						},
						{
							id: '4',
							code: '002',
							name: 'B货主',
							status: '启用',
							contactPerson: '张某',
							contactPhone: '15289896789',
							address: '上海市虹口区XXXXX',
							warehouse: '华东上海仓',
							remark: ''
						},
						{
							id: '5',
							code: '001',
							name: 'A货主',
							status: '停用',
							contactPerson: '周某',
							contactPhone: '15189896789',
							address: '上海市虹口区XXXXX',
							warehouse: '华东上海仓',
							remark: ''
						}
					]

					pagination.total = 5 // 模拟总数据量
					tableLoading.value = false
				}, 500)
			} else {
				// 实际环境API调用
				// const res = await api.getOwnerList({
				//   page: pagination.currentPage,
				//   pageSize: pagination.pageSize,
				//   ...searchForm
				// })
				// tableData.value = res.data.list
				// pagination.total = res.data.total
				tableLoading.value = false
			}
		} catch (error) {
			console.error('获取货主列表失败', error)
			tableLoading.value = false
		}
	}

	// 处理分页大小变化
	const handleSizeChange = (size) => {
		pagination.pageSize = size
		fetchTableData()
	}

	// 处理当前页变化
	const handleCurrentChange = (page) => {
		pagination.currentPage = page
		fetchTableData()
	}

	// 处理表格选择事件
	const handleSelectionChange = (rows) => {
		selectedRows.value = rows
	}

	// 处理搜索
	const handleSearch = () => {
		pagination.currentPage = 1

		// 处理搜索条件，构建API请求参数
		const params = {
			...searchForm
		};

		// 如果有地区搜索，需要特殊处理
		if (params.regionSearch) {
			// 根据项目需求，可能需要从字符串中提取省市区信息
			// 例如: "浙江省/杭州市/西湖区" => { province: "浙江省", city: "杭州市", district: "西湖区" }
			const regions = params.regionSearch.split('/');
			if (regions.length > 0) params.province = regions[0];
			if (regions.length > 1) params.city = regions[1];
			if (regions.length > 2) params.district = regions[2];
		}

		// 移除不需要的属性
		delete params.regionSearch;

		console.log('搜索参数:', params);

		// 调用获取数据函数
		fetchTableData();
	}

	// 处理添加货主
	const handleAdd = () => {
		dialogType.value = 'add'
		dialogVisible.value = true
		// 清空表单
		Object.keys(ownerForm).forEach(key => {
			if (key === 'warehouses') {
				ownerForm.warehouses = []
			} else {
				ownerForm[key] = ''
			}
		})
	}

	// 处理编辑货主
	const handleEdit = (row) => {
		dialogType.value = 'edit'
		dialogVisible.value = true

		// 填充表单数据
		Object.keys(ownerForm).forEach(key => {
			if (key === 'warehouses') {
				// 尝试从warehouse字段解析出授权分仓数组
				// 这里仅为示例，实际情况需要根据API数据结构调整
				if (row.warehouse) {
					// 假设warehouse字段存储的是逗号分隔的分仓名称
					const warehouses = row.warehouse.split(',').map(w => w.trim());
					ownerForm.warehouses = []; // 先清空

					// 检查每个可能的分仓选项
					if (warehouses.includes('华东杭州仓') || warehouses.includes('华东杭州分仓')) {
						ownerForm.warehouses.push('华东杭州分仓');
					}
					if (warehouses.includes('华南苏州仓') || warehouses.includes('华南苏州分仓')) {
						ownerForm.warehouses.push('华南苏州分仓');
					}
					if (warehouses.includes('华北上海仓') || warehouses.includes('华北上海分仓')) {
						ownerForm.warehouses.push('华北上海分仓');
					}
				} else {
					ownerForm.warehouses = [];
				}
			} else if (key === 'region') {
				// 处理region字段，获取省市区信息
				// 可以从address字段中提取，或者直接使用单独存储的region字段
				if (row.region) {
					// 如果数据库已存储省市区信息，直接使用
					ownerForm.region = row.region;
				} else if (row.address) {
					// 如果没有独立存储省市区信息，尝试从地址中提取
					// 这里假设地址格式为：省/市/区 详细地址
					const addressParts = row.address.split(' ');
					if (addressParts.length > 0) {
						const regionPart = addressParts[0];
						// 检查是否包含省市区格式（简单判断是否包含分隔符"/"）
						if (regionPart.includes('/')) {
							ownerForm.region = regionPart;
							// 详细地址可能需要更新为剩余部分
							if (addressParts.length > 1) {
								ownerForm.address = addressParts.slice(1).join(' ');
							}
						} else {
							ownerForm.region = '';
							ownerForm.address = row.address;
						}
					} else {
						ownerForm.region = '';
						ownerForm.address = row.address;
					}
				} else {
					ownerForm.region = '';
				}
			} else {
				ownerForm[key] = row[key] || '';
			}
		});
	}

	// 处理查看货主
	const handleView = (row) => {
		// 实现查看逻辑...
		console.log('查看货主', row)
	}

	// 处理日志
	const handleLog = (row) => {
		logDialogVisible.value = true

		// 模拟日志数据
		setTimeout(() => {
			logData.value = [{
					operateTime: '2024-01-05 14:30:25',
					operator: '小李',
					operateContent: `修改了货主 ${row.name} 的联系电话`
				},
				{
					operateTime: '2023-12-20 09:15:36',
					operator: '小王',
					operateContent: `修改了货主 ${row.name} 的地址信息`
				},
				{
					operateTime: '2023-11-15 16:42:10',
					operator: '小张',
					operateContent: `创建了货主 ${row.name}`
				}
			]
			logPagination.total = 3
		}, 300)
	}

	// 处理日志分页变化
	const handleLogSizeChange = (size) => {
		logPagination.pageSize = size
		// 重新获取日志数据
	}

	const handleLogCurrentChange = (page) => {
		logPagination.currentPage = page
		// 重新获取日志数据
	}

	// 处理导出
	const handleExport = () => {
		console.log('导出货主数据')
	}

	// 处理导入
	const handleImport = () => {
		console.log('导入货主数据')
	}

	// 处理启用
	const handleEnable = () => {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请选择要启用的货主')
			return
		}

		console.log('启用货主', selectedRows.value)
	}

	// 处理停用
	const handleDisable = () => {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请选择要停用的货主')
			return
		}

		console.log('停用货主', selectedRows.value)
	}

	// 处理删除操作
	const handleDelete = () => {
		if (selectedRows.value.length === 0) {
			ElMessage.warning('请先选择要删除的货主')
			return
		}
		
		ElMessage.success(`确认删除${selectedRows.value.length}个货主记录`)
		console.log('删除的货主:', selectedRows.value)
		// 这里可以调用删除API
		// deleteOwner(selectedRows.value).then(() => {
		//   ElMessage.success('删除成功')
		//   fetchTableData()
		// })
	}

	// 提交表单
	const submitForm = async () => {
		ownerFormRef.value.validate(async (valid) => {
			if (valid) {
				// 构建完整地址
				let fullAddress = '';
				if (ownerForm.region) {
					fullAddress += ownerForm.region + ' ';
				}
				if (ownerForm.address) {
					fullAddress += ownerForm.address;
				}

				// 构建提交数据
				const submitData = {
					...ownerForm,
					// 完整地址（用于显示）
					fullAddress: fullAddress.trim(),
					// 确保将warehouses转为字符串以便API保存和数据库存储
					warehouse: ownerForm.warehouses.join(','),
					// 省市区的值已经由组件处理成了字符串，直接使用
				};

				console.log('提交表单', submitData);

				try {
					// 模拟提交
					setTimeout(() => {
						ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
						dialogVisible.value = false;
						fetchTableData();
					}, 500);
				} catch (error) {
					console.error('提交表单失败', error);
				}
			}
		});
	}

	// 处理远程搜索
	const handleRemoteSearch = ({ query, prop, item }) => {
		if (prop === 'warehouse') {
			// 更新loading状态
			item.loading = true;
			
			// 模拟API请求
			setTimeout(() => {
				const warehouseOptions = [
					{ label: '华东杭州仓', value: '华东杭州仓' },
					{ label: '华东苏州仓', value: '华东苏州仓' },
					{ label: '华南广州仓', value: '华南广州仓' },
					{ label: '华北北京仓', value: '华北北京仓' },
					{ label: '西南成都仓', value: '西南成都仓' },
					{ label: '西北西安仓', value: '西北西安仓' }
				];
				
				// 根据搜索词过滤
				item.remoteOptions = query
					? warehouseOptions.filter(option => 
						option.label.toLowerCase().includes(query.toLowerCase()))
					: warehouseOptions;
				
				// 取消loading状态
				item.loading = false;
			}, 500);
		}
	}

	// 页面初始化
	onMounted(() => {
		fetchTableData()
	})
</script>

<style lang="scss" scoped>
/* 使用全局样式类，保留特殊样式覆盖 */
</style>